<?php
class CdeModulesController extends AppController {

	var $name = 'CdeModules';
	var $helpers = array('Html', 'Form', 'Element');
	var $uses=array('CdeModule','CdeAnswer','CdeUnit','CdeUsersUnit','CdeUsersModule','CdeUsersAnswer');
	/**
	 * this function checks user's answer
	 * there are two types of answer: SINGLE_ANSWER and MULTIPLE_ANSWER
	 * calculation for MULTIPLE_ANSWER
	 * redirect users to appropriate view
	 *
	 * if user does not select answers
	 * redirect user to the current page with error message
	 *
	 *
	 * @param unknown_type $question_type
	 */
	function checkanswer() {
		$userinformation=parent::beforeFilter();
		$userloggedinid=$userinformation['id'];
		$userloggedinrole=$userinformation['role'];
		$_SESSION['submit']='submitdata';
		if ($_POST['answer'] == null) {
			$this->Session->setFlash('Invalid id for answer');
			$_SESSION['messagesubmit']='You forgot to select answer';
			$this->redirect(array('action'=>'moduledetails/'.$_SESSION['unitid'].'/'.$_SESSION['currentmoduleid']));
		}
		$module=$this->CdeModule->findById($_SESSION['currentmoduleid']);
		//find last enabled module  for a particular unit
		if ($userloggedinrole=='admin') {
			$tempt=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$_SESSION['unitid']), 'order'=>'CdeModule.id DESC'));
		} else {
			$tempt=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$_SESSION['unitid'],'CdeModule.enabled'=>'1'), 'order'=>'CdeModule.id DESC'));
		}

		/**
		 * if answer is single answer then
		 * check answer id from submitted form
		 *
		 */
		if($_SESSION['questiontype']=='SINGLE_ANSWER'){
			$answer_correct=$this->CdeAnswer->find('all',array('conditions'=>array('CdeAnswer.id'=>$_POST['answer'],'CdeAnswer.correct'=>'1')));
			if (count($answer_correct)>0){
				//user's answers are correct
				//display pass message in a javascript popup window
				//redirect users to approviate view
				//if this module is last module then redirect user to unit selection
				//current module is smaller than last module, advance user to the next module
				$_SESSION['messagesubmit']=$module['CdeModule']['passmessage'];
				//delete old answers
				//update table cde_users_answers with new answer
				//add answer to users_answers table
				//add moduleid to users_modules table
				//if final module, insert unitid to user_unit table
				$this->CdeUsersAnswer->deleteOldAnswer($_SESSION['currentmoduleid'],$userloggedinid);

				$this->CdeUsersAnswer->addNewAnswer($_POST['answer'],$userloggedinid);

				$this->CdeUsersModule->addNewModule($_SESSION['currentmoduleid'],$userloggedinid);


				if ($tempt['CdeModule']['id']==$_SESSION['currentmoduleid']) {//user completed the unit
					$this->CdeUsersUnit->addNewUnit($_SESSION['unitid'],$userloggedinid);
					//$this->redirect(array('action'=>'../cde_units/viewallunits'));
					$this->redirect(array('action'=>'moduledetails/'.$_SESSION['unitid'].'/'.$_SESSION['currentmoduleid']));
				}else{

					if ($userloggedinrole=='admin') {
						$nextmodule=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$_SESSION['unitid'],'CdeModule.id >'=>$_SESSION['currentmoduleid']), 'order'=>'CdeModule.id ASC'));
					} else {
						$nextmodule=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$_SESSION['unitid'],'CdeModule.enabled'=>'1','CdeModule.id >'=>$_SESSION['currentmoduleid']), 'order'=>'CdeModule.id ASC'));
					}
					$nextmoduleid=$nextmodule['CdeModule']['id'];
					$this->redirect(array('action'=>'./moduledetails/'.$_SESSION['unitid'].'/'.$nextmoduleid),null,true);
				}
			} else {
				//user's answers are wrong
				$_SESSION['messagesubmit']=$module['CdeModule']['failmessage'];
				//redirect user
				$this->redirect(array('action'=>'moduledetails/'.$_SESSION['unitid'].'/'.$_SESSION['currentmoduleid']));
			}
		}
		if($_SESSION['questiontype']=='MULTIPLE_ANSWER'){
			$totalmark=0;
			$passmark=$module['CdeModule']['passpoint'];
			for ($i=0;$i<count($_POST['answer']);$i++) {
				//find the correct answer for current module
				$answer_correct=$this->CdeAnswer->find('all',array('conditions'=>array('CdeAnswer.id'=>$_POST['answer'][$i],'CdeAnswer.correct'=>'1')));
				if (count($answer_correct)>0) {
					//add mark for total mark
					$totalmark=$totalmark+$module['CdeModule']['rightanswerpoint'];
				}else {
					$totalmark=$totalmark-$module['CdeModule']['wronganswerpoint'];
				}
			}
			//if total mark is smaller than pass mark, user will stay at the current module.
			if ($totalmark>=$passmark) {//pass
				$_SESSION['messagesubmit']=$module['CdeModule']['passmessage'];
				//update user's answer
				//update user's completed modules
				//update user's completed unit
				$this->CdeUsersAnswer->deleteOldAnswer($_SESSION['currentmoduleid'],$userloggedinid);
				for ($i=0;$i<count($_POST['answer']);$i++) {
					//find the correct answer for current module
					//delete first and then add new answers
					$this->CdeUsersAnswer->addNewAnswer($_POST['answer'][$i],$userloggedinid);
				}
				$this->CdeUsersModule->addNewModule($_SESSION['currentmoduleid'],$userloggedinid);
				if ($tempt['CdeModule']['id']==$_SESSION['currentmoduleid']) {//final modules
					//$this->redirect(array('action'=>'../cde_units/viewallunits'));
					//add unitid and userid to cde_users_units
					$this->CdeUsersUnit->addNewUnit($_SESSION['unitid'],$userloggedinid);
					$this->redirect(array('action'=>'moduledetails/'.$_SESSION['unitid'].'/'.$_SESSION['currentmoduleid']));
				}else{//add-update cde_users_answers and cde_users_modules

					if ($userloggedinrole=='admin') {
						$nextmodule=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$_SESSION['unitid'],'CdeModule.id >'=>$_SESSION['currentmoduleid']), 'order'=>'CdeModule.id ASC'));
					} else {
						$nextmodule=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$_SESSION['unitid'],'CdeModule.enabled'=>'1','CdeModule.id >'=>$_SESSION['currentmoduleid']), 'order'=>'CdeModule.id ASC'));
					}
					$nextmoduleid=$nextmodule['CdeModule']['id'];
					$this->redirect(array('action'=>'./moduledetails/'.$_SESSION['unitid'].'/'.$nextmoduleid),null,true);
				}
			}else {//fail
				$_SESSION['messagesubmit']=$module['CdeModule']['failmessage'];
				//redirect user
				$this->redirect(array('action'=>'moduledetails/'.$_SESSION['unitid'].'/'.$_SESSION['currentmoduleid']));
			}
		}
	}
	/**
 * this function gets details of a module
 * get all enabled modules in a unit
 *
 * @param int $uid
 * @param int $mid
 */
	function moduledetails($uid = null,$mid=null) {
		$userinformation=parent::beforeFilter();
		$userloggedinid=$userinformation['id'];
		$userloggedinrole=$userinformation['role'];
		//check error urls
		//handle incorrect url entered by users
		if ($userloggedinrole=='admin') {
			$unitexist=$this->CdeUnit->find('all',array('conditions'=>array('CdeUnit.id'=>$uid)));
			$moduleexist=$this->CdeModule->find('all',array('conditions'=>array('CdeModule.id'=>$mid)));
		} else {
			$unitexist=$this->CdeUnit->find('all',array('conditions'=>array('CdeUnit.enabled'=>'1','CdeUnit.id'=>$uid), 'order'=>'CdeUnit.id ASC'));
			$moduleexist=$this->CdeModule->find('all',array('conditions'=>array('CdeModule.enabled'=>'1','CdeModule.id'=>$mid), 'order'=>'CdeModule.id ASC'));


		}
		if ($uid == null or $mid == null or empty($unitexist)or empty($moduleexist)) {
			$this->redirect(array('action'=>'../cde_units/viewallunits'));
		}

		if ($userloggedinrole=='admin') {
			$tempt1=$this->CdeModule->find('all',array('conditions'=>array('CdeModule.cde_unit_id'=>$uid), 'order'=>'CdeModule.id ASC'));
			$firstenabledmodules=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$uid), 'order'=>'CdeModule.id ASC'));
			$lastenabledmodules=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$uid), 'order'=>'CdeModule.id DESC'));
		} else {
			$tempt1=$this->CdeModule->find('all',array('conditions'=>array('CdeModule.cde_unit_id'=>$uid,'CdeModule.enabled'=>'1'), 'order'=>'CdeModule.id ASC'));
			$firstenabledmodules=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$uid,'CdeModule.enabled'=>'1'), 'order'=>'CdeModule.id ASC'));
			$lastenabledmodules=$this->CdeModule->find('first',array('conditions'=>array('CdeModule.cde_unit_id'=>$uid,'CdeModule.enabled'=>'1'), 'order'=>'CdeModule.id DESC'));
		}
		$status=$this->CdeUnit->getUnitStatus($uid, $userloggedinid);
		$tempt2=$this->CdeModule->findById($mid);



		$startmodule=$firstenabledmodules['CdeModule']['id'];
		$lastmodule=$lastenabledmodules['CdeModule']['id'];"";
		$continuemodule=$lastmodule;
		if ($status=='New') {
			$continuemodule=$startmodule;
		}else if($status=='Completed') {
			$continuemodule=$lastmodule;
		}else {
			$lastdonemodule=$this->CdeUsersModule->getContinueModule($uid,$userloggedinid);//user id
			if (count($lastdonemodule)>0) {
				$returnContinueModule=$this->CdeModule->getContinueModule($lastdonemodule[0]['cde_users_modules']['cde_module_id'],$uid,$userloggedinrole);
				if (count($returnContinueModule)>0) {//next module is the continue module
					$continuemodule=$returnContinueModule[0]['cde_modules']['id'];
				}
			}
		}
		if ($mid>$continuemodule and $userloggedinrole!='admin') {
			$this->redirect(array('action'=>'../cde_units/viewallunits'));
		}


		$answer=$this->CdeUsersAnswer->getUserAnswer($uid,$mid,$userloggedinid);
		$this->set('cdeModules',$tempt1);
		$this->set('currentModule',$tempt2);
		//set status=completed for admin to be able to click all modules
		if ($userloggedinrole=='admin') {
			$status='Completed';
		}
		$this->set('unitstatus',$status);
		$this->set('startmodule',$startmodule);
		$this->set('continuemodule',$continuemodule);
		$this->set('useranswer',$answer);
		$this->set('userloggedinrole',$userloggedinrole);

	}
	/**
	 * this function will clear all answers, modules and the unit that hae been saved
	 * the starting module is the first enabled module for the seleted unit
	 *
	 */
	function startnew($unitid=null,$moduleid=null) {
		$userinformation=parent::beforeFilter();
		$userloggedinid=$userinformation['id'];
		$userloggedinrole=$userinformation['role'];
		//delete all records in user_unit,user_module,user_answer
		$this->CdeUsersUnit->delete($unitid,$userloggedinid);
		$this->CdeUsersModule->delete($unitid,$userloggedinid);
		$this->CdeUsersAnswer->delete($unitid,$userloggedinid);
		$this->redirect(array('action'=>'moduledetails/'.$unitid.'/'.$moduleid));
	}
}
?>